<!--
*  2021-03-15
*  成品 码单列表
-->
<template>
  <div id="app" class="product">
    <!-- 头部导航 -->
    <van-nav-bar
      ref="header"
      left-arrow
      @click-left="onClickLeft"
      left-text="返回"
    >
      <template #title>
        <span @click="onClickPrev">前一天</span>
        <span @click="show = true" style="margin: 0 10px;">{{ dateTime }}</span>
        <span @click="onClickNext">后一天</span>
      </template>
      <template #right v-permissions="'100101'">
        <span @click="onClickRight"><van-icon name="plus" size="20" /></span>
      </template>
    </van-nav-bar>
    <!-- 筛选 -->
    <van-search v-model="keyLike" placeholder="请输入搜索关键词" />
    <!-- 滚动 -->
    <better-scroll
      class="public-scroll"
      :data="tableData"
      :totalPage="totalPage"
      :pulldown="true"
      @pulldown="onGetTableData"
    >
      <van-cell-group v-if="tableData.length !== 0">
        <van-cell
          v-for="(data, index) in tableData"
          :key="index"
          :title="data.title"
          :value="data.totalNum"
          @click="onClickCell(data)"
        ></van-cell>
      </van-cell-group>
      <van-empty
        class="custom-image"
        image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
        v-show="tableData.length === 0"
        description="暂无数据"
      />
    </better-scroll>

    <!-- 日期筛选 -->
    <van-calendar
      v-model="show"
      :min-date="minDate"
      :max-date="maxDate"
      :round="false"
      @confirm="onConfirm"
    />
  </div>
</template>

<script>
import { openWin, comeBack } from "@/utils/index";
import { getClothNoteList } from "@/api/product";
import dayjs from "dayjs";
import { getMacAddress } from "@/utils/auth";

export default {
  name: "product",
  data() {
    return {
      title: "",
      currentPage: 1,
      totalPage: 1,
      tableData: [],
      pageNum: 1,
      pageSize: 20,
      printStatus: true,
      show: false,
      dateTime: dayjs().format("YYYY-MM-DD"),
      minDate: new Date(dayjs().subtract(1, "year")),
      maxDate: new Date(),
      noteId: "",
      totalLength: 0,
      totalWeight: 0,
      totalNum: 0,
      yHeight: 0,
      customerId: "",
      keyLike: ''
    };
  },
  watch: {
    // 监听事件筛选
    dateTime() {
      this.onGetTableData();
    },
    // 监听customerId
    keyLike(newVal, oldVal) {
      // 防止input连续输入时，频繁发请求
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        // 异步请求
        if (oldVal !== newVal) {
          this.onGetTableData();
        }
      }, 1000);
    },
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    //初始化
    initFn(that) {
      that.onGetTableData();
    },
    // 返回
    onClickLeft() {
      comeBack();
    },
    // 前一天
    onClickPrev() {
      this.dateTime = dayjs(this.dateTime)
        .subtract(1, "day")
        .format("YYYY-MM-DD");
    },
    // 后一天
    onClickNext() {
      if (this.dateTime === dayjs().format("YYYY-MM-DD")) {
        this.$toast.fail("明天还没到");
        return false;
      }
      this.dateTime = dayjs(this.dateTime).add(1, "day").format("YYYY-MM-DD");
    },
    // 时间筛选
    onConfirm(val) {
      this.dateTime = dayjs(val).format("YYYY-MM-DD");
      this.show = false;
    },
    // 扫码
    onClickRight() {
      openWin("product-code", {
        isDetails: false,
        noteId: '',
        receiveFlag: 0,
        daySeq: 1
      });
    },
    onSearch() {
      this.onGetTableData();
    },
    // 详情 // 下拉刷新
    onGetTableData() {
      this.tableData = [];
      this.yHeight = 0;
      getClothNoteList(
        {
          title: this.dateTime,
          keyLike: this.keyLike,
        },
        (res) => {
          if (res.list.length !== 0) {
            this.tableData = res.list;
          }
        }
      );
    },
    // 码单详情
    onClickCell(data) {
      openWin("product-code", {
        isDetails: true,
        noteId: data.id,
        customerName: data.title.split('_')[1],
        customerId: data.customerId,
        receiveFlag: data.receiveFlag,
        daySeq: data.daySeq
      });
    },
    // 计算总重量/总长度
    countTotal(arr, keyName) {
      let $total = 0;
      $total = arr.reduce(function (total, currentValue) {
        console.log(currentValue[keyName]);
        return currentValue[keyName]
          ? total + Number(currentValue[keyName])
          : Number(total);
      }, 0);
      return $total;
    },
    // 判断蓝牙是否打开
    isEnabledBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .isEnabledBluetooth({}, (ret, err) => {
          if (!err) {
            if (ret.state) {
              // 已打开
              if (!getMacAddress()) {
                this.$toast.fail("如需打印，请退出登录选择打印机");
                return false;
              }
              that.getConnectState();
            } else {
              that.openBluetooth();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 打开蓝牙
    openBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .openBluetooth({}, function (ret, err) {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.connectBleByMacAddress();
            }
          } else {
            that.listenBluetoothStatus();
          }
        });
    },
    // 监听蓝牙连接状态
    listenBluetoothStatus() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .listenBluetoothStatus({}, function (ret, err) {
          if (!err) {
            if (ret.status === "STATE_ON") {
              that.connectBleByMacAddress();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 查询打印机连接状态
    getConnectState() {
      const that = this;
      that.$toast({
        message: "正在打印",
        type: "loading",
        duration: 20000,
      });
      var obj = window.api.require("xGprinterPlus");
      var ret = obj.getConnectState();
      if (ret.status) {
        let result = false;
        ret.state.forEach((bool) => {
          if (bool) {
            result = bool;
          }
        });
        if (result) {
          // 已连接
          that.$toast.clear();
          if (that.printStatus) {
            // that.setPrinterCommandType()
            that.printLabel();
          }
        } else {
          // 未连接
          that.$toast({
            type: "fail",
            message: "未连接, 请等待",
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress();
            },
          });
        }
      } else {
        // 未连接
        that.$toast({
          type: "fail",
          message: "未连接, 请等待",
          duration: 1500,
          onClose: () => {
            that.connectBleByMacAddress();
          },
        });
      }
    },
    // 设置打印模式
    setPrinterCommandType() {
      const that = this;
      let obj = window.api.require("xGprinterPlus");
      obj.setPrinterCommandType(
        {
          commandType: 1,
        },
        function (ret) {
          if (ret.status) {
            // 票据模式
            that.printLabel();
          }
        }
      );
    },
    // 连接蓝牙
    connectBleByMacAddress() {
      const that = this;
      if (that.printStatus) {
        that.$toast({
          message: "初始化打印机",
          type: "loading",
          duration: 20000,
        });
      }
      var demo = window.api.require("xGprinterPlus");
      demo.connectBleByMacAddress(
        {
          macAddress: getMacAddress() ? getMacAddress().address : "",
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.message === "已连接") {
              if (that.printStatus) {
                that.$toast({
                  type: "success",
                  message: "连接成功",
                  duration: 1500,
                  onClose: () => {
                    // that.setPrinterCommandType()
                    that.printLabel();
                  },
                });
              }
            } else if (ret.message === "连接失败") {
              that.$toast({
                type: "fail",
                message: "初始化失败",
                duration: 1500,
              });
            }
          } else {
            that.$toast({
              type: "fail",
              message: err.msg,
              duration: 1500,
            });
          }
        }
      );
    },
    // 打印数据
    printLabel() {
      const that = this;
      var obj = window.api.require("xGprinterPlus");
      obj.printLabel({
        rows: [
          {
            lineType: "size",
            width: 80,
            height: 10,
          },
          {
            lineType: "gap",
            data: 0,
          },
          {
            lineType: "cls",
          },
          {
            lineType: "gap",
            data: 0,
          },
        ],
      });

      let rows = [
        {
          lineType: "size",
          width: 80,
          height: that.yHeight + 20,
        },
        {
          lineType: "gap",
          data: 0,
        },
        {
          lineType: "cls",
        },
        {
          lineType: "gap",
          data: 0,
        },
        {
          // 日期
          lineType: "text",
          x: 16 + 2,
          y: 8,
          rotation: 0,
          xscal: 1,
          yscal: 3,
          data: "日期：" + that.dateTime,
        },
        {
          // 总长度
          lineType: "text",
          x: 16 + 2,
          y: 90,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: "总长度：" + that.totalLength,
        },
        {
          // 总重量
          lineType: "text",
          x: 16 + 220 + 2,
          y: 90,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: "总重量：" + that.totalWeight,
        },
        {
          // 总匹数
          lineType: "text",
          x: 16 + 440 + 2,
          y: 90,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: "总匹数：" + that.totalNum,
        },
        {
          // 横线
          lineType: "bar",
          x: 0,
          y: 148,
          width: 608,
          height: 2,
        },
      ];
      let parentYH = 100;
      that.tableData.forEach((items, m) => {
        parentYH = parentYH + 60;
        console.log(parentYH, m);
        let parentParams = {
          // 编号
          lineType: "text",
          x: 16 + 2,
          y: parentYH,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: "编号：" + items.details[0].designNo,
        };
        rows.push(parentParams);
        rows.push({
          // 匹数
          lineType: "text",
          x: 16 + 300 + 2,
          y: parentYH,
          rotation: 0,
          xscal: 1,
          yscal: 2,
          data: items.details.length + "匹",
        });
        items.details.forEach((item, n) => {
          let yH = parentYH + 60 * (n + 1);

          let childParamsLength = {
            // 长度
            lineType: "text",
            x: 16 + 2 + 20,
            y: yH,
            rotation: 0,
            xscal: 1,
            yscal: 2,
            data: "长度：" + item.length,
          };
          let childParamsWeight = {
            // 重量
            lineType: "text",
            x: 16 + 220 + 2 + 20,
            y: yH,
            rotation: 0,
            xscal: 1,
            yscal: 2,
            data: "重量：" + item.weight,
          };
          rows.push(childParamsLength, childParamsWeight);
          if (n === items.details.length - 1) {
            parentYH = yH;
            rows.push({
              // 横线
              lineType: "bar",
              x: 0,
              y: yH + 55,
              width: 608,
              height: 2,
            });
          }
        });
      });
      console.log(rows);
      setTimeout(() => {
        obj.printLabel(
          {
            rows: rows,
          },
          function (ret, err) {
            if (ret.status) {
              if (ret.status) {
                that.$toast.success("打印成功");
              }
            } else {
              that.$toast({
                type: "fail",
                message: err.code + err.msg,
                duration: 1500,
                onClose: () => {
                  that.connectBleByMacAddress();
                },
              });
            }
          }
        );
      }, 500);
      setTimeout(() => {
        obj.printLabel({
          rows: [
            {
              lineType: "size",
              width: 80,
              height: 10,
            },
            {
              lineType: "gap",
              data: 0,
            },
            {
              lineType: "cls",
            },
            {
              lineType: "gap",
              data: 0,
            },
          ],
        });
      }, 1000);
    },
  },
};
</script>

<style lang="scss">
.product {
  .van-search {
    position: relative;
    z-index: 999;
  }
  .van-nav-bar__title {
    display: flex;
    height: 100%;
    align-items: center;
    span {
      display: flex;
      height: 100%;
      align-items: center;
      justify-content: center;
      flex: 1;
      font-size: 14px;
      &:first-child {
        color: #1989fa;
      }
      &:last-child {
        color: #ee0a24;
      }
    }
  }
  .van-nav-bar__right {
    span {
      display: flex;
      height: 100%;
      align-items: center;
    }
  }
  .product__total {
    position: relative;
    z-index: 999;
    span {
      color: #1989fa;
      font-size: 16px;
    }
    .van-cell__title {
      flex: 0 0 36%;
    }
    .van-cell__value {
      & > div {
        display: flex;
        justify-content: space-between;
        span {
          display: line-block;
          flex: 1;
          &:first-child {
            text-align: center;
          }
        }
      }
    }
  }
  .public-scroll {
    height: calc(100vh - 94px);
    overflow: hidden;
    .product__wrapper {
      & > div {
        padding: 10px 16px;
        border-bottom: 1px solid #ddd;
        p {
          line-height: 30px;
          font-size: 18px;
          display: flex;
          justify-content: space-between;
          span {
            font-size: 12px;
            overflow: hidden;
          }
          &.product-cell {
            margin-bottom: 6px;
            span {
              display: flex;
              flex-wrap: nowrap;
              flex: 1;
              font-size: 16px;
              &:first-child {
                padding-left: 5px;
                flex: 0 0 42px !important;
                border-left: 2px solid #1989fa;
                &.active {
                  border-left-color: #ee0a24;
                }
              }
              &:last-child {
                display: flex;
                flex-wrap: wrap;
                border-bottom: 1px solid #ddd;
                & > i {
                  font-style: normal;
                  display: flex;
                  flex: 0 0 50%;
                  i {
                    font-style: normal;
                    font-weight: 700;
                    &.error {
                      color: #1989fa;
                    }
                    &.active {
                      color: #ee0a24;
                    }
                  }
                }
              }
            }
            &.active {
              background: #d9b300;
              span {
                color: #fff;
              }
            }
          }
          &:last-child {
            padding-top: 10px;
            span {
              font-weight: 800;
              font-size: 16px;
            }
          }
        }
      }
    }
  }
  .product-btn {
    height: 80px;
    padding: 16px;
    background: whitesmoke;
    &.van-hairline--top-bottom::after,
    .van-hairline-unset--top-bottom::after {
      border-width: 0;
    }
  }
}
</style>
